package Socket02;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 聊天室服务端
 */
public class Server {
    private ServerSocket serverSocket;

    public Server() {
        try {
            System.out.println("服务端等待建立....");
            serverSocket = new ServerSocket(8801);
            System.out.println("一个服务端已建立");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        while (true){
            try {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端已连接");

                Thread t1 = new Thread(new ClientHandler(socket));
                t1.start();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    class ClientHandler implements Runnable{
        private Socket socket;
        private String id;

        public ClientHandler(Socket socket){
            this.socket = socket;
            id = socket.getInetAddress().getHostAddress();
        }
        @Override
        public void run() {
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream()));
                String s;
                while ((s = br.readLine()) != null){
                    System.out.println(id+"说："+s);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


